<template>
  <el-dialog
      :model-value="visible"
      title="居民档案"
      width="80%"
      @close="handleClose"
  >
    <!-- 切换按钮 -->
    <div class="tab-buttons">
      <el-button
          :type="activeTab === 'detail' ? 'primary' : 'text'"
          @click="activeTab = 'detail'"
      >
        居民详情
      </el-button>
      <el-button
          :type="activeTab === 'health' ? 'primary' : 'text'"
          @click="activeTab = 'health'"
      >
        健康档案
      </el-button>
      <el-button
          :type="activeTab === 'records' ? 'primary' : 'text'"
          @click="activeTab = 'records'"
      >
        健康记录
      </el-button>
    </div>

    <!-- 居民详情内容 -->
    <div v-if="activeTab === 'detail'">
      <el-descriptions
          title="基本信息"
          :column="4"
          border
          class="description-box"
      >
        <el-descriptions-item label="居民编号">{{ residents.residentId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ residents.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ residents.gender }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ residents.dateOfBirth }}</el-descriptions-item>

        <el-descriptions-item label="身份证号" :span="2">{{ residents.idCard }}</el-descriptions-item>
        <el-descriptions-item label="手机号码" :span="2">{{ residents.phoneNumber }}</el-descriptions-item>

        <el-descriptions-item label="民族">{{ residents.ethnicity }}</el-descriptions-item>
        <el-descriptions-item label="籍贯" :span="3">{{ residents.birthplace }}</el-descriptions-item>

        <el-descriptions-item label="现居地" :span="4">{{ residents.currentAddress }}</el-descriptions-item>
      </el-descriptions>

      <!-- 其他信息部分 -->
      <el-descriptions
          title="其他信息"
          :column="4"
          border
          class="description-box"
      >
        <el-descriptions-item label="文化程度">{{ residents.educationLevel }}</el-descriptions-item>
        <el-descriptions-item label="婚姻状况">{{ residents.maritalStatus }}</el-descriptions-item>
        <el-descriptions-item label="职业" :span="2">{{ residents.occupation }}</el-descriptions-item>

        <el-descriptions-item label="工作单位" :span="4">{{ residents.workUnit }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 健康档案内容 -->
    <div v-if="activeTab === 'health'" class="health-record">
      <el-descriptions title="健康档案" :column="2" border>
        <el-descriptions-item label="身高">{{ healthInfo.height || '未记录' }} cm</el-descriptions-item>
        <el-descriptions-item label="体重">{{ healthInfo.weight || '未记录' }} kg</el-descriptions-item>

        <el-descriptions-item label="血型">{{ healthInfo.bloodType || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="RH因子">{{ healthInfo.rh || '未知' }}</el-descriptions-item>

        <el-descriptions-item label="过敏史" :span="2">
          {{ healthInfo.allergyHistory && healthInfo.allergyHistory.length ? healthInfo.allergyHistory : '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="既往病史" :span="2">
          {{
            healthInfo.pastMedicalHistory && healthInfo.pastMedicalHistory.length ? healthInfo.pastMedicalHistory : '无'
          }}
        </el-descriptions-item>

        <el-descriptions-item label="就诊史" :span="2">
          {{ healthInfo.medicalHistory && healthInfo.medicalHistory.length ? healthInfo.medicalHistory : '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="家族病史" :span="2">
          {{ healthInfo.familyHistory && healthInfo.familyHistory.length ? healthInfo.familyHistory : '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 健康记录内容（优化后） -->
    <div v-if="activeTab === 'records'" class="health-records-panel">
      <div class="health-records-container">
        <!-- 左侧 ECharts 图表（拆分为4张独立图表） -->
        <div class="echarts-container">
          <h3>健康测量轨迹</h3>
          <!-- 图表网格布局容器 -->
          <div class="echarts-grid">
            <!-- 血糖图表 -->
            <div class="echarts-item">
              <h4 class="chart-title">血糖(mmol/L)</h4>
              <div ref="bloodGlucoseChart" class="chart-dom"></div>
            </div>
            <!-- 血压图表 -->
            <div class="echarts-item">
              <h4 class="chart-title">血压(mmHg)</h4>
              <div ref="bloodPressureChart" class="chart-dom"></div>
            </div>
            <!-- 体重图表 -->
            <div class="echarts-item">
              <h4 class="chart-title">体重(kg)</h4>
              <div ref="weightChart" class="chart-dom"></div>
            </div>
            <!-- 心率图表 -->
            <div class="echarts-item">
              <h4 class="chart-title">心率(次/分钟)</h4>
              <div ref="heartRateChart" class="chart-dom"></div>
            </div>
          </div>
        </div>

        <!-- 右侧最近数据列表（优化排版） -->
        <div class="recent-records">
          <!-- 血糖记录表格（带独立表头与分隔符） -->
          <div class="records-table-group">
            <h4 class="table-header">血糖记录</h4>
            <el-table
                :data="bloodGlucoseRecordsList"
                style="width: 100%"
                height="220"
                empty-text="暂无血糖记录数据"
                border
                size="default"
            >
              <el-table-column prop="measurementType" label="餐前/餐后" width="100" align="center"/>
              <el-table-column prop="glucoseValue" label="血糖(mmol/L)" width="120" align="center"/>
              <el-table-column prop="measurementDate" label="测量时间" min-width="140" align="center"/>
            </el-table>
          </div>

          <!-- 分隔符 -->
          <div class="table-divider"></div>

          <!-- 血压记录表格（带独立表头与分隔符） -->
          <div class="records-table-group">
            <h4 class="table-header">血压记录</h4>
            <el-table
                :data="bloodPressureRecordsList"
                style="width: 100%"
                height="220"
                empty-text="暂无血压记录数据"
                border
                size="default"
            >
              <el-table-column prop="systolicPressure" label="收缩压(mmHg)" width="120" align="center"/>
              <el-table-column prop="diastolicPressure" label="舒张压(mmHg)" width="120" align="center"/>
              <el-table-column prop="measurementDate" label="测量时间" min-width="140" align="center"/>
            </el-table>
          </div>

          <!-- 分隔符 -->
          <div class="table-divider"></div>

          <!-- 体重记录表格（带独立表头与分隔符） -->
          <div class="records-table-group">
            <h4 class="table-header">体重记录</h4>
            <el-table
                :data="weightRecordsList"
                style="width: 100%"
                height="220"
                empty-text="暂无体重记录数据"
                border
                size="default"
            >
              <el-table-column prop="weightValue" label="体重(千克)" width="120" align="center"/>
              <el-table-column prop="measurementDate" label="测量时间" min-width="140" align="center"/>
            </el-table>
          </div>

          <!-- 分隔符 -->
          <div class="table-divider"></div>

          <!-- 心率记录表格（带独立表头） -->
          <div class="records-table-group">
            <h4 class="table-header">心率记录</h4>
            <el-table
                :data="heartRateRecordsList"
                style="width: 100%"
                height="220"
                empty-text="暂无心率记录数据"
                border
                size="default"
            >
              <el-table-column prop="heartRate" label="心率(次/分钟)" width="120" align="center"/>
              <el-table-column prop="measurementDate" label="测量时间" min-width="140" align="center"/>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import * as echarts from 'echarts'; // 引入 ECharts

export default {
  name: 'ResidentsDetail',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    details: {
      type: Object,
      default: () => ({}),
    },
    healthRecord: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['update:visible'],
  data() {
    return {
      // 原有数据保持不变，新增以下图表假数据
      // 七天健康数据假数据（按周一到周日顺序）
      chartFakeData: {
        // 血糖：mmol/L（正常范围3.9-6.1）
        bloodGlucose: [],
        // 血压：收缩压/舒张压（正常收缩压90-139，舒张压60-89）
        bloodPressure: {
          systolic: [], // 收缩压
          diastolic: [] // 舒张压
        },
        // 体重：kg
        weight: [],
        // 心率：次/分钟（正常范围60-100）
        heartRate: []
      },
      // 存储四张图表实例
      charts: {
        bloodGlucose: null,
        bloodPressure: null,
        weight: null,
        heartRate: null
      },
      residents: {},
      healthInfo: {},
      bloodGlucoseRecordsList: [],
      bloodPressureRecordsList: [],
      weightRecordsList: [],
      heartRateRecordsList: [],
      activeTab: 'detail', // 默认显示居民详情
    };
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'records') {
        this.$nextTick(() => {
          this.initAllCharts(); // 改为初始化所有图表
        });
      } else {
        this.destroyAllCharts(); // 切换时销毁所有图表
      }
    },
    visible(newVal) {
      if (!newVal) {
        this.destroyAllCharts(); // 关闭对话框销毁图表
      }
    }
  },
  mounted() {
    this.bindInfo()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose(); // 销毁 ECharts 实例
    }
  },
  methods: {
    // 计算合适的Y轴范围（基于数据值动态调整）
    calculateYAxisRange(dataArray) {
      // 处理空数据情况
      if (!dataArray || dataArray.length === 0) {
        return {min: 0, max: 100}; // 空数据时使用默认范围
      }

      // 提取有效数值（过滤非数字）
      const validData = dataArray.filter(val => typeof val === 'number' && !isNaN(val));
      if (validData.length === 0) {
        return {min: 0, max: 100};
      }

      // 计算数据的最大最小值
      const minVal = Math.min(...validData);
      const maxVal = Math.max(...validData);

      // 计算数据范围
      const range = maxVal - minVal;

      // 如果所有数据都相同（范围为0），设置一个合理范围
      if (range === 0) {
        return {
          min: minVal - 1, // 向下扩展1单位
          max: maxVal + 1  // 向上扩展1单位
        };
      }

      // 计算缓冲值（取范围的15%作为上下缓冲，避免数据贴边）
      const buffer = range * 0.15;

      // 计算最终范围（确保最小值不小于0，适合健康数据）
      return {
        min: Math.max(0, minVal - buffer), // 不小于0
        max: maxVal + buffer
      };
    },
    bindInfo() {
      console.log(this.details)
      this.residents = this.details.residents
      this.healthInfo = this.details.healthInfo
      this.bloodGlucoseRecordsList = this.details.bloodGlucoseRecordsList
      this.bloodPressureRecordsList = this.details.bloodPressureRecordsList
      this.weightRecordsList = this.details.weightRecordsList
      this.heartRateRecordsList = this.details.heartRateRecordsList
      this.bloodGlucoseRecordsList.forEach(item => {
        this.chartFakeData.bloodGlucose.push(item.glucoseValue);
      })
      this.bloodPressureRecordsList.forEach(item => {
        this.chartFakeData.bloodPressure.systolic.push(item.systolicPressure);
        this.chartFakeData.bloodPressure.diastolic.push(item.diastolicPressure);
      })
      this.weightRecordsList.forEach(item => {
        this.chartFakeData.weight.push(item.weightValue);
      })
      this.heartRateRecordsList.forEach(item => {
        this.chartFakeData.heartRate.push(item.heartRate);
      })
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    // 初始化所有图表
    initAllCharts() {
      this.initBloodGlucoseChart();
      this.initBloodPressureChart();
      this.initWeightChart();
      this.initHeartRateChart();
    },
    // 血糖图表
    initBloodGlucoseChart() {
      const dom = this.$refs.bloodGlucoseChart;
      if (!dom) return;

      // 计算动态范围
      const yRange = this.calculateYAxisRange(this.chartFakeData.bloodGlucose);

      if (this.charts.bloodGlucose) {
        this.charts.bloodGlucose.dispose();
      }
      this.charts.bloodGlucose = echarts.init(dom);
      const option = this.getBaseChartOption({
        data: this.chartFakeData.bloodGlucose,
        color: '#FF6B6B',
        yMin: yRange.min.toFixed(1), // 使用动态计算的最小值
        yMax: yRange.max.toFixed(1),  // 使用动态计算的最大值
        yInterval: 1 // 血糖Y轴间距：1
      });
      this.charts.bloodGlucose.setOption(option);
    },

// 血压图表
    initBloodPressureChart() {
      const dom = this.$refs.bloodPressureChart;
      if (!dom) return;

      // 血压需要合并收缩压和舒张压数据计算范围
      const allPressureData = [
        ...this.chartFakeData.bloodPressure.systolic,
        ...this.chartFakeData.bloodPressure.diastolic
      ];
      const yRange = this.calculateYAxisRange(allPressureData);

      if (this.charts.bloodPressure) {
        this.charts.bloodPressure.dispose();
      }
      this.charts.bloodPressure = echarts.init(dom);
      const option = {
        ...this.getBaseChartOption({
          color: '#4ECDC4',
          data: [],
          yMin: yRange.min.toFixed(0), // 动态范围
          yMax: yRange.max.toFixed(0),  // 动态范围
          yInterval: 10 // 血压Y轴间距：10
        }),
        series: [
          {
            name: '收缩压',
            type: 'line',
            data: this.chartFakeData.bloodPressure.systolic,
            lineStyle: {color: '#4ECDC4', width: 2},
            itemStyle: {color: '#4ECDC4'}
          },
          {
            name: '舒张压',
            type: 'line',
            data: this.chartFakeData.bloodPressure.diastolic,
            lineStyle: {color: '#1A535C', width: 2, type: 'dashed'},
            itemStyle: {color: '#1A535C'}
          }
        ],
        yAxis: {
          ...this.getBaseChartOption().yAxis,
          min: yRange.min,
          max: yRange.max,
          name: 'mmHg'
        }
      };
      this.charts.bloodPressure.setOption(option);
    },

// 体重图表
    initWeightChart() {
      const dom = this.$refs.weightChart;
      if (!dom) return;

      const yRange = this.calculateYAxisRange(this.chartFakeData.weight);

      if (this.charts.weight) {
        this.charts.weight.dispose();
      }
      this.charts.weight = echarts.init(dom);
      const option = this.getBaseChartOption({
        data: this.chartFakeData.weight,
        color: '#FFD166',
        yMin: yRange.min.toFixed(1),
        yMax: yRange.max.toFixed(1),
        yInterval: 0.5
      });
      this.charts.weight.setOption(option);
    },

// 心率图表
    initHeartRateChart() {
      const dom = this.$refs.heartRateChart;
      if (!dom) return;

      const yRange = this.calculateYAxisRange(this.chartFakeData.heartRate);

      if (this.charts.heartRate) {
        this.charts.heartRate.dispose();
      }
      this.charts.heartRate = echarts.init(dom);
      const option = this.getBaseChartOption({
        data: this.chartFakeData.heartRate,
        color: '#6A0572',
        yMin: yRange.min.toFixed(0),
        yMax: yRange.max.toFixed(0),
        yInterval: 2
      });
      this.charts.heartRate.setOption(option);
    },
    // 获取图表基础配置（复用通用样式）
// 优化后的 getBaseChartOption 方法（添加参数默认值）
    getBaseChartOption({
                         data = [],
                         color = '#409EFF',
                         yMin = null,
                         yMax = null
                       } = {}) {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          //  tooltip 优化：显示“第N次测量”而非日期（与隐藏的x轴刻度对应）
          formatter: (params) => {
            const index = params[0].dataIndex + 1; // 计算是第几次测量（1-7次）
            return `第${index}次测量: ${params[0].value}${params[0].seriesName === '血压' ? '' : params[0].axisY.name}`;
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '25%', // 增加底部间距，避免横轴名称被遮挡
          top: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisTick: {show: false},
          axisLine: {show: false},
          axisLabel: {show: false},
          // 完全隐藏横轴名称
          name: '', // 清空名称文本
          nameShow: false, // 显式关闭显示

          // 同时调整网格布局，回收底部空间
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%', // 底部间距改小，充分利用空间
            top: '5%',
            containLabel: true
          }
        },
        yAxis: {
          type: 'value',
          min: yMin,
          max: yMax,
          nameTextStyle: {fontSize: 10},
          axisLabel: {fontSize: 10}
        },
        series: [
          {
            type: 'line',
            data: data,
            smooth: true,
            lineStyle: {color: color, width: 2},
            itemStyle: {color: color, radius: 3},
            symbol: 'circle',
            symbolSize: 6
          }
        ],
        legend: {show: false}
      };
    },
    // 销毁所有图表
    destroyAllCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart && chart.dispose) {
          chart.dispose();
        }
      });
      // 重置图表实例对象
      this.charts = {
        bloodGlucose: null,
        bloodPressure: null,
        weight: null,
        heartRate: null
      };
    }
  },
};
</script>

<style scoped>
.tab-buttons {
  margin-bottom: 20px;
}

.description-box {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: center;
}

.health-record {
  max-height: 60vh;
  overflow-y: auto;
}

/* 健康记录面板样式 */
.health-records-panel {
  height: 60vh;
}

.health-records-container {
  display: flex;
  height: 100%;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.echarts-container {
  flex: 1;
  padding: 15px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.echarts-container h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #409EFF;
}

.recent-records {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.recent-records h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409EFF;
}

/* 原有样式保持不变，新增以下优化样式 */
/* 表格组容器：控制表格间距 */
.records-table-group {
  margin-bottom: 16px;
}

/* 表格独立表头：增强视觉识别 */
.table-header {
  margin: 0 0 8px;
  padding-left: 8px;
  font-size: 15px;
  color: #333;
  border-left: 3px solid #409EFF;
  font-weight: 500;
}

/* 表格分隔符：清晰区分不同数据类型 */
.table-divider {
  height: 1px;
  margin: 8px 0;
  background-color: #e6e6e6;
}

/* 表格单元格优化：提升可读性 */
.el-table th {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
}

.el-table td {
  vertical-align: middle !important;
}

/* 图表容器布局：2x2网格排列 */
.echarts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr; /* 两列等宽 */
  grid-template-rows: 1fr 1fr; /* 两行等高 */
  gap: 12px; /* 图表之间间距 */
  height: calc(100% - 36px); /* 减去标题高度，占满剩余空间 */
}

/* 单个图表项容器 */
.echarts-item {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  padding: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 图表标题样式 */
.chart-title {
  margin: 0 0 6px;
  font-size: 12px;
  color: #666;
  font-weight: 500;
  text-align: left;
}

/* 图表DOM容器：固定高度 */
.chart-dom {
  width: 100%;
  height: calc(100% - 20px); /* 减去标题高度 */
  min-height: 120px;
}

/* 响应式适配：小屏幕时改为1列布局 */
@media (max-width: 1200px) {
  .echarts-grid {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(4, 1fr);
  }
}
</style>